import { type ComponentPublicInstance } from 'vue'
import type { ComponentMetadata } from './types/core'

type ComponentId = string

interface ComponentRegistration {
  id: ComponentId
  instance: ComponentPublicInstance
  metadata: ComponentMetadata
}

class ComponentRegistry {
  private components = new Map<ComponentId, ComponentRegistration>()

  /**
   * 注册组件到注册中心
   */
  register(
    componentId: ComponentId,
    instance: ComponentPublicInstance,
    metadata: ComponentMetadata = { id: componentId },
  ) {
    // 检查组件ID唯一性
    if (this.components.has(componentId)) {
      console.warn(`Component with ID '${componentId}' already registered.`)
      return
    }

    // 创建注册项
    const registration: ComponentRegistration = {
      id: componentId,
      instance,
      metadata,
    }

    // 存储注册信息
    this.components.set(componentId, registration)
    console.debug(`Component registered: ${componentId}`)
  }

  /**
   * 注销组件
   */
  unregister(componentId: ComponentId) {
    if (!this.components.has(componentId)) return

    this.components.delete(componentId)
    console.debug(`Component unregistered: ${componentId}`)
  }

  /**
   * 获取组件实例
   */
  getComponent<T = ComponentPublicInstance>(componentId: ComponentId): T | null {
    const registration = this.components.get(componentId)
    return (registration?.instance as T) || null
  }

  /**
   * 检查组件是否存在
   */
  hasComponent(componentId: ComponentId): boolean {
    return this.components.has(componentId)
  }
}

// 导出全局单例
export const componentRegistry = new ComponentRegistry()
